<template>
  <view class="bg-[#f5f5f5] min-h-screen w-full box-border overflow-x-hidden">
    <!-- Header -->
    <PageHeader title="" :showBack="true" :onlyBack="true"/>
    <view class="bg-gradient-to-r from-[#165DFF] to-[#6f47ff] text-white p-[40rpx] text-center relative overflow-hidden rounded-b-2xl">
      <view class="absolute w-[300rpx] h-[300rpx] bg-white bg-opacity-10 rounded-full -top-[100rpx] -right-[80rpx]" />
      <text class="text-[44rpx] font-bold mb-[15rpx] block relative z-2">充值中心</text>
      <text class="text-[28rpx] opacity-90 relative z-2">选择适合您的会员类型，享受更多平台特权</text>
    </view>

    <!-- 当前会员状态 -->
    <view class="flex justify-center px-[32rpx] -mt-[36rpx] relative z-10 mb-[40rpx]">
      <view class="bg-white rounded-2xl p-[32rpx] shadow-md w-full max-w-[680rpx] text-center">
        <view class="w-[80rpx] h-[80rpx] bg-gradient-to-r from-[#165DFF] to-[#6f47ff] rounded-full flex items-center justify-center text-white text-[36rpx] mx-auto mb-[25rpx]">
          <IconFont font-class-name="iconfont" class-prefix="icon" name="yirenzhengyonghu" size="36"/>
        </view>
        <text class="text-[34rpx] font-semibold mb-[15rpx] text-[#165DFF] block">当前会员状态</text>
        <text class="text-[30rpx] font-bold mb-[25rpx] block">{{ userStore.userInfo.vip == 1 ? "SVIP会员" : "普通会员" }}</text>
        <text class="text-[26rpx] text-[#666] leading-[1.8] mb-[25rpx] block">
          您当前是
          <text class="text-[#FF4D4F] font-bold">
            {{ userStore.userInfo.vip == 1 ? "SVIP会员" : "普通会员" }}
          </text>
            ，任务完成后平台将扣除
          <text class="text-[#FF4D4F] font-bold">{{ userStore.userInfo.vip == 1 ? "6%" : "15%" }}</text>
          信息服务费
        </text>
        <view v-if="userStore.userInfo.vip != 1" class="bg-gradient-to-r from-[#FFB300] to-[#FF4D4F] text-white px-[25rpx] py-[10rpx] rounded-2xl text-[28rpx] font-semibold inline-block">
          升级会员可节省服务费
        </view>
      </view>
    </view>

    <view class="px-[24rpx] pb-[40rpx] w-full max-w-[750rpx] box-border mx-auto">
      <!-- 选择会员类型 -->
      <view class="text-center mb-[35rpx]">
        <text class="text-[34rpx] font-semibold text-[#165DFF] relative">选择会员类型</text>
        <view class="w-[120rpx] h-[5rpx] bg-gradient-to-r from-[#165DFF] to-[#6f47ff] rounded-[5rpx] mx-auto mt-[20rpx]" />
      </view>
      <view class="flex flex-col md:flex-row gap-[32rpx] mb-[50rpx]">
        <!-- 年费会员 -->
        <view class="rounded-2xl p-[32rpx] text-center shadow-md bg-white flex-1 min-w-0">
          <IconFont name="calendar-alt" class="text-[60rpx] text-[#165DFF] mb-[25rpx]" />
          <text class="text-[32rpx] font-bold mb-[15rpx] text-[#165DFF] block">年费会员</text>
          <!-- 价格显示区域 -->
          <view class="mb-[30rpx]">
            <!-- 优惠标签 -->
            <view class="flex justify-center mb-[16rpx]">
              <view class="bg-gradient-to-r from-[#FF4D4F] to-[#FF6B6B] text-white px-[16rpx] py-[6rpx] rounded-full text-[22rpx] font-semibold shadow-sm">
                🎉 限时优惠
              </view>
            </view>
            
            <!-- 价格对比 -->
            <view class="flex items-center justify-center mb-[12rpx]">
              <text class="text-[26rpx] text-[#999] line-through mr-[16rpx]">原价 ¥200</text>
              <view class="bg-[#FFE7E7] text-[#FF4D4F] px-[12rpx] py-[4rpx] rounded-[8rpx] text-[20rpx] font-medium border border-[#FFB3B3]">
                立省 ¥180
              </view>
            </view>
            
            <!-- 现价突出显示 -->
            <view class="text-center">
              <text class="text-[48rpx] font-bold text-[#FF4D4F] leading-none">
                ¥{{ 20 }}
              </text>
              <text class="text-[26rpx] text-[#666] ml-[8rpx] font-medium">/年</text>
            </view>
            
            <!-- 性价比提示 -->
            <!-- <view class="text-center mt-[12rpx]">
              <text class="text-[22rpx] text-[#52C41A] font-medium">
                💰 平均每月仅 ¥{{ Math.round((vipList[0]?.price || 180) / 12) }}
              </text>
            </view> -->
          </view>
          
          <view class="text-left text-[26rpx] mb-[35rpx]">
            <view v-for="(item, idx) in yearBenefits" :key="idx" class="py-[12rpx] pl-[40rpx] relative border-b border-b-dashed border-b-[#eee] last:border-b-0 flex items-center">
              <view class="absolute left-0 top-[50%] -translate-y-1/2 w-[30rpx] h-[30rpx] bg-[#e8f0fe] rounded-full flex items-center justify-center">
                <text class="text-[#165DFF] font-bold text-[22rpx]">✓</text>
              </view>
              <text class="ml-[40rpx]">{{ item }}</text>
            </view>
          </view>
          <view class="bg-[#f5f7fa] rounded-xl p-[20rpx] mb-[30rpx]">
            <view class="text-[26rpx] font-semibold mb-[10rpx] text-[#165DFF] flex items-center justify-center">
              <IconFont name="percentage" class="mr-[10rpx]" />
              <text>扣费规则</text>
            </view>
            <view class="text-[24rpx] text-[#666]">
              <view v-for="(item, idx) in yearRules" :key="idx" class="mb-[8rpx] pl-[25rpx] relative flex items-center">
                <text class="text-[#165DFF] font-bold absolute left-0">•</text>
                <text class="ml-[24rpx]">{{ item }}</text>
              </view>
            </view>
          </view>
          <nut-button v-if="userStore.userInfo.vip == 0" type="primary" size="large" class="w-full text-[30rpx] font-semibold bg-gradient-to-r from-[#165DFF] to-[#6f47ff] rounded-2xl mt-[8rpx] shadow-lg hover:shadow-xl transition-all duration-300" @click="handlePurchase(1)">
            🚀 立即开通年费会员
          </nut-button>
          <nut-button v-else type="primary" size="large" disabled class="w-full text-[30rpx] font-semibold bg-gradient-to-r from-[#165DFF] to-[#6f47ff] rounded-2xl mt-[8rpx] shadow-lg hover:shadow-xl transition-all duration-300">
            您已经是年费会员
          </nut-button>
        </view>
        <!-- 次卡会员 -->
        <view v-if="false" class="rounded-2xl p-[32rpx] text-center shadow-md bg-white flex-1 min-w-0 border-2 border-[#165DFF] relative -translate-y-[10rpx]">
          <view class="absolute -top-[15rpx] left-1/2 -translate-x-1/2 bg-gradient-to-r from-[#FFB300] to-[#FF4D4F] text-white px-[32rpx] py-[8rpx] rounded-2xl text-[22rpx] font-semibold">
            超值
          </view>
          <IconFont name="ticket-alt" class="text-[60rpx] text-[#165DFF] mb-[25rpx]" />
          <text class="text-[32rpx] font-bold mb-[15rpx] text-[#165DFF] block">次卡会员</text>
          <!-- 价格显示区域 -->
          <view class="mb-[30rpx]">
            <!-- 优惠标签 -->
            <view class="flex justify-center mb-[16rpx]">
              <view class="bg-gradient-to-r from-[#FFB300] to-[#FF6B6B] text-white px-[16rpx] py-[6rpx] rounded-full text-[22rpx] font-semibold shadow-sm">
                ⭐ 超值推荐
              </view>
            </view>
            
            <!-- 价格对比 -->
            <view class="flex items-center justify-center mb-[12rpx]">
              <text class="text-[26rpx] text-[#999] line-through mr-[16rpx]">原价 ¥100</text>
              <view class="bg-[#FFF7E6] text-[#FFB300] px-[12rpx] py-[4rpx] rounded-[8rpx] text-[20rpx] font-medium border border-[#FFD591]">
                立省 ¥10
              </view>
            </view>
            
            <!-- 现价突出显示 -->
            <view class="text-center">
              <text class="text-[48rpx] font-bold text-[#FF4D4F] leading-none">
                ¥{{ vipList[1]?.price || 90 }}
              </text>
              <text class="text-[26rpx] text-[#666] ml-[8rpx] font-medium">/10次</text>
            </view>
            
            <!-- 性价比提示 -->
            <view class="text-center mt-[12rpx]">
              <text class="text-[22rpx] text-[#52C41A] font-medium">
                💎 平均每次仅 ¥{{ Math.round((vipList[1]?.price || 90) / 10) }}
              </text>
            </view>
          </view>
          <view class="text-left text-[26rpx] mb-[35rpx]">
            <view v-for="(item, idx) in cardBenefits" :key="idx" class="py-[12rpx] pl-[40rpx] relative border-b border-b-dashed border-b-[#eee] last:border-b-0 flex items-center">
              <view class="absolute left-0 top-[50%] -translate-y-1/2 w-[30rpx] h-[30rpx] bg-[#165DFF] rounded-full flex items-center justify-center">
                <text class="text-white font-bold text-[22rpx]">✓</text>
              </view>
              <text class="ml-[40rpx]">{{ item }}</text>
            </view>
          </view>
          <view class="bg-[#f5f7fa] rounded-xl p-[20rpx] mb-[30rpx]">
            <view class="text-[26rpx] font-semibold mb-[10rpx] text-[#165DFF] flex items-center justify-center">
              <IconFont name="money-bill-wave" class="mr-[10rpx]" />
              <text>扣费规则</text>
            </view>
            <view class="text-[24rpx] text-[#666]">
              <view v-for="(item, idx) in cardRules" :key="idx" class="mb-[8rpx] pl-[20rpx] relative flex items-center">
                <text class="text-[#165DFF] font-bold absolute left-0">•</text>
                <text class="ml-[24rpx]">{{ item }}</text>
              </view>
            </view>
          </view>
          <nut-button type="primary" size="large" class="w-full text-[30rpx] font-semibold bg-gradient-to-r from-[#165DFF] to-[#6f47ff] rounded-2xl mt-[8rpx] shadow-lg hover:shadow-xl transition-all duration-300" @click="handlePurchase(1)">
            ⚡ 立即购买10次卡
          </nut-button>
        </view>
      </view>

      <!-- 费用对比表格 -->
      <view class="bg-white rounded-2xl p-[32rpx] shadow-md mb-[40rpx] overflow-x-auto">
        <text class="text-[32rpx] font-semibold text-[#165DFF] mb-[24rpx] text-center block">会员费用对比</text>
        <view class="min-w-full">
          <view class="flex bg-[#f5f7fa] rounded-t-xl">
            <view class="flex-1 p-[20rpx] text-[26rpx] font-semibold text-[#165DFF] text-center">扣费项目</view>
            <view class="flex-1 p-[20rpx] text-[26rpx] font-semibold text-[#165DFF] text-center">普通会员</view>
            <view class="flex-1 p-[20rpx] text-[26rpx] font-semibold text-[#165DFF] text-center">年费会员</view>
            <!-- <view class="flex-1 p-[20rpx] text-[26rpx] font-semibold text-[#165DFF] text-center">次卡会员</view> -->
          </view>
          <view v-for="(row, idx) in tableRows" :key="idx" class="flex border-b border-[#eee] last:border-0">
            <view class="flex-1 p-[20rpx] text-[24rpx] text-center">{{ row[0] }}</view>
            <view class="flex-1 p-[20rpx] text-[24rpx] text-center" :class="row[1].class">{{ row[1].text }}</view>
            <view class="flex-1 p-[20rpx] text-[24rpx] text-center" :class="row[2].class">{{ row[2].text }}</view>
            <!-- <view class="flex-1 p-[20rpx] text-[24rpx] text-center" :class="row[3].class">{{ row[3].text }}</view> -->
          </view>
        </view>
      </view>

      <!-- 常见问题 -->
      <view class="bg-white rounded-2xl p-[32rpx] shadow-md mb-[40rpx]">
        <text class="text-[32rpx] font-semibold text-[#165DFF] mb-[24rpx] text-center block">常见问题解答</text>
        <view class="space-y-[24rpx]">
          <view v-for="(faq, idx) in faqs" :key="idx" class="mb-[24rpx] pb-[24rpx] border-b border-[#eee] last:border-0">
            <view class="text-[28rpx] font-semibold mb-[12rpx] text-[#333] flex items-center">
              <text class="mr-[12rpx]">❓</text>
              <text>{{ faq.q }}</text>
            </view>
            <text class="text-[24rpx] text-[#666] leading-[1.8] pl-[32rpx]">{{ faq.a }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Footer -->
    <!-- <view class="text-center p-[32rpx] text-[#165DFF] text-[22rpx]">
      <text class="block">© 2023 平台服务商中心 | 专业服务，高效合作</text>
      <view class="flex justify-center gap-[30rpx] mt-[16rpx] flex-wrap">
        <text class="text-[#165DFF]">会员协议</text>
        <text class="text-[#165DFF]">扣费规则</text>
        <text class="text-[#165DFF]">客服支持</text>
        <text class="text-[#165DFF]">隐私政策</text>
      </view>
    </view> -->

    <!-- 支付方式选择弹窗 -->
    <PaymentMethodModal 
      v-model="showPaymentModal" 
      :amount="currentVipPrice"
      @confirm="handlePaymentConfirm"
      @cancel="handlePaymentCancel"
    />
  </view>
</template>

<script setup lang="ts">
import { IconFont } from '@nutui/icons-vue-taro'
import PageHeader from '@/components/PageHeader.vue'
import PaymentMethodModal from '@/components/PaymentMethodModal.vue'
import { useUserStore } from '@/store/user'
import { post } from '@/utils/request'
import { onMounted, ref } from 'vue'
import Taro from "@tarojs/taro";


const userStore = useUserStore()
const vipList = ref<any>([])

// 支付方式选择弹窗相关
const showPaymentModal = ref(false);
const currentVipPrice = ref(0);
const currentVipType = ref(0);


onMounted(async () => {
  await userStore.fetchUserInfo()
  console.log("user", userStore.userInfo)

  const res = await post('/dictionary/merchantVip', {
   
  })
  console.log(res)
  vipList.value = res.data.map((item: any) => item.columns)
})


const yearBenefits = [
  '一年内无限次发布任务',
  '任务完成扣点仅6%',
  '提现免手续费',
  '优先推荐展示',
  '专属客服支持'
]
const yearRules = [
  '任务结束后扣6%服务费',
  '提现时不再扣除任何手续费'
]
const cardBenefits = [
  '10次任务发布权限',
  '按次收费，不限任务金额',
  '任务完成无额外扣点',
  '提现免手续费',
  '适合低频任务发布'
]
const cardRules = [
  '每次任务消耗1次卡',
  '任务金额100%结算',
  '无任何额外百分比扣点',
  '提现时不再扣除手续费'
]
const tableRows = [
  [
    '会员费用',
    { text: '¥0', class: '' },
    { text: '¥200/年', class: 'text-[#FF4D4F] font-bold' },
    { text: '¥299/10次', class: 'text-[#FF4D4F] font-bold' }
  ],
  [
    '任务服务费',
    { text: '15%', class: 'text-[#FF4D4F] font-bold' },
    { text: '6%', class: 'text-[#16C784] font-bold' },
    { text: '0%', class: 'text-[#16C784] font-bold' }
  ],
  [
    '提现手续费',
    { text: '0%', class: '' },
    { text: '0%', class: 'text-[#16C784] font-bold' },
    { text: '0%', class: 'text-[#16C784] font-bold' }
  ],
  [
    '适合场景',
    { text: '偶尔使用', class: '' },
    { text: '高频使用', class: '' },
    { text: '低频使用', class: '' }
  ],
  [
    '任务金额',
    { text: '¥8,500', class: '' },
    { text: '¥9,500', class: 'text-[#16C784] font-bold' },
    { text: '¥10,000', class: 'text-[#16C784] font-bold' }
  ]
]
const faqs = [
  {
    q: '年费会员和次卡会员有什么区别？',
    a: '年费会员按年付费，适合高频发布任务的用户，每笔任务仅扣除6%服务费；次卡会员按次数付费（10次卡），适合低频用户，每次任务消耗一次卡，无额外百分比扣点。'
  },
  {
    q: '任务完成后资金如何结算？',
    a: '年费会员：任务结束后平台扣除6%服务费；次卡会员：任务金额100%结算到您的账户（每次任务消耗一次卡）。'
  },
  {
    q: '提现是否有手续费？',
    a: '年费会员和次卡会员提现均免手续费，普通服务商提现需支付1%手续费。'
  },
  {
    q: '次卡会员的有效期是多久？',
    a: '次卡会员购买后永久有效，无使用时间限制，用完为止。'
  }
]
function handlePurchase(type: number) {
  if(userStore.userInfo.is_buy == 0) {
    Taro.showToast({title: '您不能购买会员！', icon: 'error', duration: 2000})
    return
  }
  const obj = vipList.value[type];
  // 显示支付方式选择弹窗
  showPaymentModal.value = true;
  currentVipPrice.value = obj.price;
  currentVipType.value = obj.id;
}

/**
 * 处理支付方式确认
 * @param method 支付方式
 */
const handlePaymentConfirm = async (method: 'balance' | 'wechat') => {
  try {
    // 调用支付接口
    const payRes = await post('/pay/vip', {
      "amount": currentVipPrice.value,
      "vipType": currentVipType.value,
      "openId": userStore.userInfo.id,
      "deductionBalance": method === 'balance' ? 1 : 0, // 余额支付传1，微信支付传0
    });

    if (payRes.code == 0) {
      if (method === 'wechat') {
        // 微信支付
        (window as any).WeixinJSBridge.invoke('getBrandWCPayRequest', {
          "appId": payRes.data.appid,     //公众号ID，由商户传入
          "timeStamp": payRes.data.timeStamp,     //时间戳，自1970年以来的秒数
          "nonceStr": payRes.data.nonceStr,      //随机串
          "package": payRes.data.prepayId,
          "signType": "RSA",     //微信签名方式：
          "paySign": payRes.data.paySign //微信签名
        },
        function(res: any) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
            Taro.showToast({title: '购买成功！', icon: 'success', duration: 2000})
            setTimeout(() => {
              userStore.fetchUserInfo();
              Taro.navigateBack();
            }, 2000);
          }
          else{
            Taro.showToast({title: '购买失败！', icon: 'error', duration: 2000})
          }
        });
      } else {
        // 余额支付
        if (payRes.data.code == 2) {
          // 余额支付成功
          Taro.showToast({
            title: "购买成功！",
            icon: "success",
            duration: 2000,
          });
          // 更新用户余额
          const newBalance = (userStore.userInfo.balance || 0) - currentVipPrice.value;
          userStore.updateBalance(newBalance);
          // 刷新用户信息
          setTimeout(() => {
            userStore.fetchUserInfo();
            Taro.navigateBack();
          }, 2000);
        } else {
          // 余额支付失败
          Taro.showToast({
            title: payRes.data.msg || "购买失败",
            icon: "error",
            duration: 2000,
          });
        }
      }
    } else {
      Taro.showToast({
        title: "购买失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("购买失败:", error);
    Taro.showToast({
      title: "购买失败，请重试",
      icon: "none",
    });
  }
};

/**
 * 处理支付取消
 */
const handlePaymentCancel = () => {
  Taro.showToast({
    title: "已取消购买",
    icon: "none",
  });
};

</script>